package org.jeecg.modules.basic.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basic.demo.bed.entity.LwgyBaseBed;
import org.jeecg.modules.basic.demo.bed.service.ILwgyBaseBedService;
import org.jeecg.modules.basic.demo.student.entity.LwgyBaseStudent;
import org.jeecg.modules.basic.demo.student.service.ILwgyBaseStudentService;
import org.jeecg.modules.basic.entrance.entity.LwgyEntranceGuard;
import org.jeecg.modules.basic.entrance.service.ILwgyEntranceGuardService;
import org.jeecg.modules.basic.entry.entity.LwgyAbnormalAction;
import org.jeecg.modules.basic.entry.entity.LwgyInoutRecord;
import org.jeecg.modules.basic.entry.service.ILwgyAbnormalActionService;
import org.jeecg.modules.basic.entry.service.ILwgyInoutRecordService;
import org.jeecg.modules.basic.entry.util.StringUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @author sn
 * @date 2022-09-23 15:20
 *  //当天0点-前一天0点前出去 2 但是没有回来的学生，得看student表中的学生最后状态，不能看过程表
 *
 */
@Slf4j
public class NoBackAbnormalInfoJob implements Job {

    @Autowired
    private ILwgyInoutRecordService lwgyInoutRecordService;

    @Autowired
    private ILwgyBaseStudentService lwgyBaseStudentService;

    @Autowired
    private ILwgyAbnormalActionService lwgyAbnormalActionService;
    @Autowired
    private ILwgyBaseBedService lwgyBaseBedService;

//    @Value("${wechat.corpId}")
//    private String corpId;
//
//    @Value("${wechat.corpSecret}")
//    private String corpSecret;
//
//    @Value("${wechat.agentld}")
//    private String agentld;



    @SneakyThrows
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" 时间:" + DateUtils.getTimestamp()));
        //得到一个Calendar实例
        Calendar calendar = Calendar.getInstance();
        //calendar的日期设为今天
        calendar.setTime(new Date());
        //设置calendar为昨天
        calendar.add(Calendar.DATE, -1);
        Date yesterday = calendar.getTime();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //前一天的字符串
        String pre = simpleDateFormat.format(yesterday);
        //前一天凌晨0点的字符串
        String startTime = pre.substring(0, 10) + " 00:00:00";
        //前一天午夜24点的字符串
        String endTime = pre.substring(0, 10) + " 24:00:00";


        QueryWrapper<LwgyBaseStudent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("last_direction", "2");
//        queryWrapper.eq("student_college","1731495433815560193");
        queryWrapper.ge("last_direction_time", startTime);
        queryWrapper.lt("last_direction_time", endTime);
       // queryWrapper.between("last_direction_time",startTime,endTime);//出去的时间在昨天零点-今天零点，且没有回来的叫未归
        List<LwgyBaseStudent> wglist = lwgyBaseStudentService.getListByJob(queryWrapper);

        //循环wglist ,写入异常表
        if(wglist.size()>0){
            //  通过学生id获取原床位信息
            String[] ids = wglist.stream().map(p -> p.getId()).collect(Collectors.toList()).toArray(new String[0]);
            List<LwgyBaseBed> bedList = lwgyBaseBedService.getBedListByStuId2(ids);
            //获取学院信息床位信息end
            List<LwgyAbnormalAction> endList = new ArrayList<LwgyAbnormalAction>();
            wglist.stream().forEach(item->{
                LwgyAbnormalAction lwgyAbnormalAction = new LwgyAbnormalAction();
                //添加学院信息
                lwgyAbnormalAction.setStudentid(item.getId());
                lwgyAbnormalAction.setStudentXy(item.getStudentCollege());
                lwgyAbnormalAction.setStudentZy(item.getStudentMajor());
                lwgyAbnormalAction.setStudentBj(item.getStudentClass());
                lwgyAbnormalAction.setStudentSex(item.getStudentSex());
                List<LwgyBaseBed> bedsList = bedList.stream().filter(d -> d.getStudentId().equals(item.getId())).collect(Collectors.toList());
                if(oConvertUtils.isNotEmpty(bedsList) && bedsList.size()>0){
                    //添加床位信息
                    LwgyBaseBed lwgyBaseBed = bedsList.get(0);
                    lwgyAbnormalAction.setCampus(lwgyBaseBed.getCampusName());
                    lwgyAbnormalAction.setBuildingNum(lwgyBaseBed.getBuildingName());
                    lwgyAbnormalAction.setUnit(lwgyBaseBed.getUnitName());
                    lwgyAbnormalAction.setRoomNum(lwgyBaseBed.getRoomName());
                    lwgyAbnormalAction.setBedNum(lwgyBaseBed.getName());
                }

                lwgyAbnormalAction.setStuStatus("2");//abnormal_inout 字典 1晚归，2未归 3长时间未归，4长时间未进
                lwgyAbnormalAction.setStudentName(item.getStudentName());
                lwgyAbnormalAction.setStudentNumber(item.getStudentNumber());
                lwgyAbnormalAction.setLastIntoStatus(item.getLastDirection());

                String str1 = item.getLastDirectionTime();
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date myDate1 = null;
                try {
                    myDate1 = sdf1.parse(str1);
                }catch (Exception e){
                    e.printStackTrace();
                }

                lwgyAbnormalAction.setLastIntoTime(myDate1);
                endList.add(lwgyAbnormalAction);
            });
            lwgyAbnormalActionService.saveBatch(endList);
//            XWPFDocument document = new XWPFDocument();
//            XWPFParagraph paragraph = document.createParagraph();
//            XWPFRun run = paragraph.createRun();
//            for (LwgyAbnormalAction item : endList){
//                run.setText(String.valueOf(item));
//                run.addBreak(BreakType.TEXT_WRAPPING);
//            }
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            document.write(out);
//            byte[]bytes = out.toByteArray();
//            Resource resource = new ByteArrayResource(bytes);
//            return
            exportNoBackeExcel(endList);

        }

       /* List<LwgyEntranceGuard> list = lwgyEntranceGuardServic.list();
        //晚归的pushtype好像是1
        List<LwgyEntranceGuard> checkList = list.stream().filter(item ->
                item.getPushType().equals("1")).collect(Collectors.toList());
        if(oConvertUtils.isNotEmpty(checkList) && checkList.size()>0){
            //存在晚归的设置，可以进行推送
            LwgyEntranceGuard map = (LwgyEntranceGuard) checkList.get(0);
            String entranceTime = map.getEntranceTime();//超过这个时间的就算晚归
            if(oConvertUtils.isEmpty(entranceTime)){
                entranceTime="22:00";//没设置时间按照晚上十点算
            }
            String dateFormat =DateUtils.now();
            System.out.println("今天时间"+dateFormat);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间格式
            Date date = new Date(); //当前时间
            Calendar calendar = Calendar.getInstance(); //得到日历
            calendar.setTime(date);//把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -1); //设置为前一天
            String beforeOneDay = sdf.format(calendar.getTime()); //得到前一天的时间
            String endTime = beforeOneDay.substring(0, 10) + " "+entranceTime+":00";
            System.out.println("endTime:"+endTime);
            QueryWrapper<LwgyInoutRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("direction", "1");
            queryWrapper.between("record_date",endTime,dateFormat);//进入时间小于当前时间，//晚于今天前一天的最晚时间，算晚归
            List<LwgyInoutRecord> wglist = lwgyInoutRecordService.list(queryWrapper);//---=====  关联查询xy,bed 等信息，一起保存
            //循环wglist ,写入异常表
            if(wglist.size()>0){
                List<LwgyAbnormalAction> endList = new ArrayList<LwgyAbnormalAction>();
                wglist.stream().forEach(item->{
                    LwgyAbnormalAction lwgyAbnormalAction = new LwgyAbnormalAction();
                    lwgyAbnormalAction.setStuStatus("1");//晚归
                    lwgyAbnormalAction.setStudentName(item.getUserName());
                    lwgyAbnormalAction.setStudentNumber(item.getUserId());
                    lwgyAbnormalAction.setLastIntoStatus(item.getDirection());
                    lwgyAbnormalAction.setLastIntoTime(item.getRecordDate());
                    endList.add(lwgyAbnormalAction);
                    });
                lwgyAbnormalActionService.saveBatch(endList);

            }
        }*/
    }

//    public void exportWord(List<LwgyAbnormalAction> endList)throws IOException {
//        XWPFDocument document = new XWPFDocument();
//        XWPFParagraph paragraph = document.createParagraph();
//        XWPFRun run = paragraph.createRun();
//        for (LwgyAbnormalAction lwgyAbnormalAction:endList){
//            run.setText(String.valueOf(lwgyAbnormalAction));
//            run.addBreak(BreakType.TEXT_WRAPPING);
//        }
//        try (FileOutputStream out = new FileOutputStream("\\docs\\")){
//            document.write(out);
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//    }
@GetMapping(value = "/exportNoBackeExcel", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<InputStreamResource> exportNoBackeExcel(@RequestParam("endList") List<LwgyAbnormalAction> endList) throws IOException {
//    XWPFDocument document = new XWPFDocument();
//    XWPFParagraph paragraph = document.createParagraph();
//    XWPFRun run = paragraph.createRun();
//    for (LwgyAbnormalAction lwgyAbnormalAction : endList) {
//        run.setText(String.valueOf(lwgyAbnormalAction));
//        run.addBreak(BreakType.TEXT_WRAPPING);
//    }
    Workbook workbook = new XSSFWorkbook(); // 新建一个工作簿对象
    Sheet sheet = workbook.createSheet("Students"); // 创建一个工作表对象
    // 创建表头行
    Row headerRow = sheet.createRow(0);
    headerRow.createCell(0).setCellValue("姓名");
    headerRow.createCell(1).setCellValue("性别");
    headerRow.createCell(2).setCellValue("学号");
    headerRow.createCell(3).setCellValue("校区");
    headerRow.createCell(4).setCellValue("学院");
    headerRow.createCell(5).setCellValue("班级");
    headerRow.createCell(6).setCellValue("楼号");
    headerRow.createCell(7).setCellValue("单元");
    headerRow.createCell(8).setCellValue("房间号");
    headerRow.createCell(9).setCellValue("床位号");
    headerRow.createCell(10).setCellValue("学生异动状态");
    headerRow.createCell(11).setCellValue("最后进出状态");
    headerRow.createCell(12).setCellValue("最后进出时间");

//填充数据行
    for (int i = 0; i< endList.size();i++){
        LwgyAbnormalAction lwgyAbnormalAction = endList.get(i);
        Row dataRow =sheet.createRow(i+1);
        dataRow.createCell(0).setCellValue(lwgyAbnormalAction.getStudentName());
        dataRow.createCell(2).setCellValue(lwgyAbnormalAction.getStudentNumber());
        String sex = lwgyAbnormalAction.getStudentSex();
        String gender;
        if (sex.equals("1")){
            gender = "男";
        }else if (sex.equals("2")){
            gender = "女";
        }else{
            gender = "未知";
        }
        String lastIntoStatus = lwgyAbnormalAction.getLastIntoStatus();
        String status;
        if (lastIntoStatus.equals("1")){
            status = "进";
        }else if (lastIntoStatus.equals("2")){
            status = "出";
        }else {
            status = "未知";
        }
        String studentStatus = lwgyAbnormalAction.getStuStatus();
        String stustatus;
        if (studentStatus.equals("2")){
            stustatus = "未归";
        }else {
            stustatus = "未知";
        }
        dataRow.createCell(1).setCellValue(gender);
        dataRow.createCell(3).setCellValue(lwgyAbnormalAction.getCampus());
        dataRow.createCell(4).setCellValue(lwgyAbnormalAction.getStudentXy());
        dataRow.createCell(5).setCellValue(lwgyAbnormalAction.getStudentBj());
        dataRow.createCell(6).setCellValue(lwgyAbnormalAction.getBuildingNum());
        dataRow.createCell(7).setCellValue(lwgyAbnormalAction.getUnit());
        dataRow.createCell(8).setCellValue(lwgyAbnormalAction.getRoomNum());
        dataRow.createCell(9).setCellValue(lwgyAbnormalAction.getBedNum());
        dataRow.createCell(10).setCellValue(stustatus);
        dataRow.createCell(11).setCellValue(status);
        dataRow.createCell(12).setCellValue(lwgyAbnormalAction.getLastIntoTime());
    }
    // 指定要保存的路径和文件名word
//    String filePath = "C:\\Users\\Lenovo\\Desktop\\test\\test.xlsx";
//    FileOutputStream fileOut = new FileOutputStream(filePath);
//    document.write(fileOut);
//    fileOut.close();
    //指定要保存的路径和文件名excel
    File file = new File("C:\\Users\\Lenovo\\Desktop\\test\\未归记录.xlsx");
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    workbook.write(fileOutputStream); // 将工作簿写入文件输出流中
    fileOutputStream.close(); // 关闭文件输出流

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
    return ResponseEntity.ok()
            .header("Content-Disposition", "attachment; filename=enlist.xlsx")
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

}
